package com.example.bm.common.handler;

import com.example.common.domain.Layui;
import com.example.common.exception.FileDownloadException;
import com.example.common.exception.LimitAccessException;
import com.example.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

/**
 * 异常统一处理
 *
 * @author bryceM
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class BmGlobalExceptionHandler {

    /**
     * 全局异常
     *
     * @param
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Layui handleException(Exception e) {
        log.error("系统内部异常，异常信息", e);
        return Layui.error("系统内部异常");
    }

    /**
     * service 异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public Layui handleServiceException(ServiceException e) {
        log.error(e.getMessage(), e);
        return Layui.error(e.getMessage());
    }

    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return Layui
     */
    @ExceptionHandler(BindException.class)
    public Layui validExceptionHandler(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Layui.error(((Integer) HttpStatus.BAD_REQUEST.value()).toString(), message.toString());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return Layui
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Layui handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return Layui.error(((Integer) HttpStatus.BAD_REQUEST.value()).toString(), message.toString());
    }

    @ExceptionHandler(value = LimitAccessException.class)
    public Layui handleLimitAccessException(LimitAccessException e) {
        log.debug("LimitAccessException", e);
        return Layui.error(((Integer) HttpStatus.TOO_MANY_REQUESTS.value()).toString(), e.getMessage());
    }

    @ExceptionHandler(value = FileDownloadException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void handleFileDownloadException(FileDownloadException e) {
        log.error("FileDownloadException", e);
    }

//    @ExceptionHandler(value = UnauthorizedException.class)
//    public FebsResponse handleUnauthorizedException(UnauthorizedException e) {
//        log.debug("UnauthorizedException", e);
//        return new FebsResponse().code(HttpStatus.FORBIDDEN).message(e.getMessage());
//    }
//
//    @ExceptionHandler(value = AuthenticationException.class)
//    public FebsResponse handleAuthenticationException(AuthenticationException e) {
//        log.debug("AuthenticationException", e);
//        return new FebsResponse().code(HttpStatus.INTERNAL_SERVER_ERROR).message(e.getMessage());
//    }
//
//    @ExceptionHandler(value = AuthorizationException.class)
//    public FebsResponse handleAuthorizationException(AuthorizationException e) {
//        log.debug("AuthorizationException", e);
//        return new FebsResponse().code(HttpStatus.UNAUTHORIZED).message(e.getMessage());
//    }
//
//
//    @ExceptionHandler(value = ExpiredSessionException.class)
//    public FebsResponse handleExpiredSessionException(ExpiredSessionException e) {
//        log.debug("ExpiredSessionException", e);
//        return new FebsResponse().code(HttpStatus.UNAUTHORIZED).message(e.getMessage());
//    }


}
